//
//  CZRefreshControl.swift
//  01-自定义下拉刷新控件
//
//  Created by smile on 2017/8/4.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
// 控件高度
private let CZRefreshControlH: CGFloat = 50
// 记录自定义下拉刷新控件状态
enum CZRefreshControlType: String{
    case normal = "正常中"
    case pulling = "下拉中"
    case refreshing = "刷新中"
}
class CZRefreshControl: UIControl {
    
    var closure:(()->())?
    
    // 记录父控件
    var scrollView: UIScrollView?
    // 记录当前的状态
    var type: CZRefreshControlType = .normal{
        didSet{
            // 通过枚举名获取枚举名的值
            messageLabel.text = type.rawValue
            switch type {
            case .normal:
                // 因为只有在刷新中才会加上顶部的50
                // oldValue 记录的是上一个值
                if oldValue == .refreshing {
                    // 设置动画
                    UIView.animate(withDuration: 0.25, animations: {
                        // 顶部边界减50
                        self.scrollView?.contentInset.top -= CZRefreshControlH
                    }, completion: { (_) in
                        // 停止菊花动画
                        self.indicatorView.stopAnimating()
                        // 显示箭头
                        self.pull_refreshImageView.isHidden = false
                    })
                }
                
                // 设置动画
                UIView.animate(withDuration: 0.25, animations: { 
                    // 恢复原状
                    self.pull_refreshImageView.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    
                })
                
                
            case .pulling:
                // 设置箭头动画
                UIView.animate(withDuration: 0.25, animations: { 
                    self.pull_refreshImageView.transform = CGAffineTransform(rotationAngle: CGFloat(-3*M_PI))
                    
                }, completion: { (_) in
                    
                })
            case .refreshing:

                UIView.animate(withDuration: 0.25, animations: {
                    // 顶部边界加50
                    self.scrollView?.contentInset.top += CZRefreshControlH
                    // 隐藏箭头
                    self.pull_refreshImageView.isHidden = true
                    // 菊花动画
                    self.indicatorView.startAnimating()
                }, completion: { (_) in
                    // 告知外界刷新
                    self.sendActions(for: UIControlEvents.valueChanged)
//                    self.closure?()
                })
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -CZRefreshControlH, width: UIScreen.main.bounds.width, height: CZRefreshControlH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 结束刷新动画
    func endRefreshing(){
        type = .normal
    }
    
    // 监听其自己将要添加到哪个父控件身上
    override func willMove(toSuperview newSuperview: UIView?) {
       
        //判断newSuperview是否存在 而且是否可以滚动
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        // 注册观察者
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
        // 记录
        self.scrollView = scrollView
        
    }
    
    // 观察者的实现
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        // 记录
        let contentOffSetY = self.scrollView!.contentOffset.y
        // 代表用户拖拽着tableView
        if self.scrollView!.isDragging {
            // 临界点
            // >= -114  && type == .pulling
            if contentOffSetY >= -114 && type == .pulling{
                type = .normal
            }else if contentOffSetY < -114, type == .normal{
                type = .pulling
            }
        }else{
            // 停止拖拽
            if type == .pulling {
                type = .refreshing
            }
        }
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.orange
        addSubview(messageLabel)
        addSubview(pull_refreshImageView)
        addSubview(indicatorView)
        //系统约束
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        pull_refreshImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: pull_refreshImageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: pull_refreshImageView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        

    }
    
    // MARK: - 懒加载控件
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.text = "正常中"
        lab.textColor = UIColor.white
        // 居中
        lab.textAlignment = .center
        return lab
    }()
    // 箭头
    private lazy var pull_refreshImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 风火轮
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView()
    
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
